import React, { useEffect, useState, useReducer, createRef,useRef,useContext} from 'react';
import classNames from "classnames";
import {
  Switch,
  Route,
  useHistory,
  Link
} from "react-router-dom";
import sdk from 'qcloud-iotexplorer-h5-panel-sdk';
import { useDeviceData } from '../hooks/useDeviceData';
import {  List, InputItem , Toast, DatePicker,} from 'antd-mobile';
import { InputUserPage } from './InputUserPage';
import { WeightEchart } from './QsPage';
import PubSub from 'pubsub-js' //引入
import { createStore } from 'redux';
import moment from 'moment';
// import the core library.
import ReactEChartsCore from 'echarts-for-react/lib/core';
import * as echarts from 'echarts/core';
import {
  RadarChart
} from 'echarts/charts';
import {
  GridComponent,
  TooltipComponent,
  TitleComponent,
  LegendComponent
} from 'echarts/components';
import {
  CanvasRenderer,
} from 'echarts/renderers';
echarts.use(
  [TitleComponent, TooltipComponent, GridComponent,LegendComponent, RadarChart, CanvasRenderer]
);
const resage = ["<实际",">=实际"]
const resbmrRange = ["不⾜","标准"]
const resbmiWHORange = ["偏瘦","健康","偏胖","肥胖"]
const resFatRange1 = ["偏瘦","健康","警戒","轻度肥胖","重度肥胖"]
const resweightRange = ["不⾜","过轻","标准","过重","肥胖"]
const resMuscleRange = ["不⾜","标准","优"]
const resFatRange2 = ["偏低","正常","偏⾼"]
const resWaterRange = ["缺失","标准","优"]
const resBoneRange = ["偏低","正常","优"]
const resFatRange = ["正常","偏⾼","严重偏⾼"]
const resbodyShape = ["无","隐性胖","偏胖型","运动型偏胖","缺乏锻炼型","标准型","标准运动型","偏瘦型","偏瘦运动型","运动健美型"]
const resNutrition = ["无","严重营养不良","中度营养不良","营养不良","标准","营养过剩","营养严重过剩"]
const resobesity = ["较轻","正常","轻度肥胖","中度肥胖","重度肥胖","极度肥胖"]

const apirul = "https://iotapi.sziton.com/api/appapi/"
const imgrul = "https://iotapi.sziton.com/afile/SRGBQ283TZ/"

// const store = createStore(cr);
// 当前时间
const current_time = new Date()
const windowHeight = window.innerHeight || document.documentElement.clientHeight;
let myuserInfo = sdk.userInfo
const c_type = 3
// 目标体重
const mbweight = 68.00
export function Jkcard(){
  const [state, {
    onDeviceDataChange,
    onDeviceStatusChange
  }] = useDeviceData(sdk);
  const weight_unitmode = state.templateMap["weight_unit"].define.mapping[state.deviceData.weight_unit]
  const weight_unit = weight_unitmode == undefined ? "kg" : weight_unitmode
  useEffect(() => {
    // 检查固件更新，若有可升级固件，且设备在线，则弹出提示
    const doCheckFirmwareUpgrade = async () => {
      try {
        const upgradeInfo = await sdk.checkFirmwareUpgrade({
          silent: false, // 设置为 true 则只检查，不弹出提示
        });
        console.log('firmware upgrade info', upgradeInfo);
      } catch (err) {
        console.error('checkFirmwareUpgrade fail', err);
      }
    };
    doCheckFirmwareUpgrade();
  }, []);
  const history = useHistory()
  // 三方用户数据
	const [userinforef, setUserinforef] = useState({});
	const para_user1 = useRef(userinforef);
  var userinfo
  // 设备状态
  const [tzl,settzl] = useState([]);
  const [lasttzl,setlasttzl] = useState({});
  const [shangcitzl,setshangcitzl] = useState({});
  // 是否有用户
  const [isuserinfo,setIsuserinfo] = useState();
  const getThirdUserInfo =() =>{
    // 获取三方用户数据
    console.log('开始获取三方用户数据')
    var request = require('superAgent')
    request
    .post(apirul+'getThirdUserInfo')
    .send({     
      "productId":sdk.productId,
      "deviceName":sdk.deviceName,
      "thirdUserId":id,
      // "thirdUserId":third_user_id,
      "wx_unionid":myuserInfo.UserID,
    })
    .end(function(err, res){
      if(res.code = 1){
        var userinfo = JSON.parse(res.text).u_info
        console.log('获取三方用户数据如下：')
        console.log(userinfo)
      }else{
        console.log('服务器出错'+res)
      }
    })
  }
  const getLastUserData =() =>{
    var request = require('superAgent')
    request
    .post(apirul+'getlastuserinfo_tx')
    .send({
      "productId":sdk.productId,
      "deviceName":sdk.deviceName,
      "wx_unionid":myuserInfo.UserID,
      "username":myuserInfo.NickName,
      "userimg":myuserInfo.Avatar,
    })
    .end(function(err, res){
      if(res.body.code == 1){
        setUserinforef(res.body.data.third_user)
        getThirdUserDataBYNum(res.body.data.third_user.id)
        userinfo = res.body.data.third_user
        para_user1.current = res.body.data.third_user
        if(userinfo.height == null || userinfo.height == "" || userinfo.birthday == null || userinfo.sex == null){
          console.log("用户信息为空!")
          // 用户信息为空
          var isinput=true
          Toast.fail('用户信息不完整，无法计算体脂！请先录入数据！', 2,history.push('/InputUserPage',isinput))
        }
      }else{
        console.log('服务器'+res)
      }
      console.log('res',res)
    })
  }
  const getThirdUserDataBYNum =(id) =>{
    var request = require('superAgent')
    request
    .post(apirul+'getThirdUserDataBYNum')
    .send({
      "thirdUserId":id,
      "num":7
    })
    .end(function(err, res){
      if(res.body.code = 1){
        console.log('res',res)
        var JkcardUdata = res.body.data.data
        settzl(JkcardUdata);
        if(JkcardUdata.length > 1){
          setlasttzl(JkcardUdata[0])
          setshangcitzl(JkcardUdata[1])
        }else{
          setlasttzl(JkcardUdata[0])
          setshangcitzl(JkcardUdata[0])
        }
      }else{
        console.log('服务器'+res.status,res)
      }
    })
  }  
  
  useEffect(() => {
    getLastUserData()
    getData(apirul+'getlastuserinfo_tx',{
      "productId":sdk.productId,
      "deviceName":sdk.deviceName,
      "wx_unionid":myuserInfo.UserID,
      "username":myuserInfo.NickName,
      "userimg":myuserInfo.Avatar,
    }).then(function onFulfilled(value){
      console.log('数据为：')
      console.log(value.third_user)
      const pubsubTest =value.third_user
      PubSub.publish('third_user',pubsubTest)//发布消息		//appDta 是发布名称，pubsubTest 是传递参数
      // setUserinforef(value.third_user)
      // getThirdUserDataBYNum(res.body.data.third_user.id)
      // userinfo = res.body.data.third_user
      // para_user1.current = res.body.data.third_user
      // if(userinfo.height == null || userinfo.height == "" || userinfo.birthday == null || userinfo.sex == null){
      //   console.log("用户信息为空!")
      //   // 用户信息为空
      //   var isinput=true
      //   Toast.fail('用户信息不完整，无法计算体脂！请先录入数据！', 2,history.push('/InputUserPage',isinput))
      // }
    }).catch(function onRejected(error){
      console.log('服务器错误'+error)
    });

    console.log("++++++++")
    console.log(parseInt(0x01D3, 16))
    console.log(parseInt(0x008b, 16))
    console.log(para_user1)
    console.log(userinfo)

    // 消息订阅
    PubSub.subscribe('third_user',(msg, pubsubTest) => {		//msg 指'appData'方法， pubsubTest 指传过来的参数
      console.log("PubSub")		//appData
      // this.subTest = pubsubTest
      console.log(msg)		//appData
      console.log(pubsubTest)		//pubsubTest
      PubSub.unsubscribe("third_user");
    })
  }, [])
  return(
    <div style={{ minHeight: `${windowHeight}px` }}>
    <Switch>
        <Route path="/Home" exact><Home para_user1={para_user1} tzl={tzl} lasttzl={lasttzl} shangcitzl={shangcitzl} weight_unit={weight_unit}/></Route>
        <Route path="/InputUserPage" exact>
          <InputUserPage para_user1={para_user1} isuserinfo={isuserinfo}/>
        </Route>
        <Route path="/TjtzPage" exact><TjtzPage /></Route>
        <Route path="/TjtwPage" exact><TjtwPage /></Route>
        <Route path="/UserInfo" exact><UserInfo /></Route>
        <Route path="/LssjPage" exact><LssjPage /></Route>
        <Route path="/CsbgPage" exact><CsbgPage para_user1={para_user1} weight_unit={weight_unit}/></Route>
        <Route path="/LjczPage" exact><LjczPage para_user1={para_user1}/></Route>
        <Route path="/"><Home  para_user1={para_user1} tzl={tzl} lasttzl={lasttzl} shangcitzl={shangcitzl} weight_unit={weight_unit}/></Route>
    </Switch>
    </div>
  )
}
export function Home(props) {
  // useDeviceData包含以下值，deviceData，deviceStatus，templateMap，templateList
  // 设备状态
  const tzl= props.tzl == undefined ? [] : props.tzl;
  const lasttzl= props.lasttzl == undefined ? [] : props.lasttzl;
  const shangcitzl = props.shangcitzl == undefined ? [] : props.shangcitzl;
  const weight_unit = props.weight_unit == undefined ? 1 : props.weight_unit;
  // 三方用户数据
  const para_user1 = props.para_user1 == undefined ? [] : props.para_user1;
  // 设备读取体重
  const weight =lasttzl!= undefined ? lasttzl.weight_7 : "00.00"
  // 设备控制增加时间戳
  const [lastControl, setLastControl] = useState();
  // XXXX测量
  const wdate =lasttzl == undefined ? "" : moment(parseInt(lasttzl.option_time)).format("MM月DD日 HH:mm");
  // 历史数据 
  const weightlist = tzl.map(function(item,index) {
    return (
      item.weight_7
    )
  });
  const week = ["一","二","三","四","五","六","日"]
  const lssj = week.map(function(item,index) {
    var czdata =weightlist.length > index ? weightlist[index] :"未测"
    return (
    <div className="fl-cc circle" key={week[index]}>
      <div>{czdata}</div>
      <div>{item}</div>
    </div>
    )
  });
  const Mbweight = () =>{
    const mbw = (weight-mbweight).toFixed(2)
    if( mbw== 0){return "你已完成目标！"}
    else if(mbw > 0){return ("距离目标还需要减重"+mbw + weight_unit)}
    else if(mbw < 0){return ("距离目标还需要增重"+Math.abs(mbw) + weight_unit)}
    else{return "加载中..."}
  }
  // 跳转
  const history = useHistory()
  function ljcz(){
    history.push('/LjczPage')
  }
  //对比上次
  const dbweight =shangcitzl!= undefined && lasttzl!= undefined && lasttzl.weight_7!= null && shangcitzl.weight_7!= null ? (lasttzl.weight_7 - shangcitzl.weight_7).toFixed(2) : 0
  const dbtzldata =shangcitzl!= undefined && lasttzl!= undefined && lasttzl.body_fat_per!= null && shangcitzl.body_fat_per!= null ? (lasttzl.body_fat_per - shangcitzl.body_fat_per).toFixed(2) : 0
  const sharetitle = "思迈德体脂秤"
  // const sharetitle = "", imgUrl: shareimgurl 分享图片地址可选
  const share = () =>{
    console.log("分享")
    sdk.setShareConfig({ title: sharetitle }).then(
      (res) => {console.log(res)},  // 成功
      (err) => {console.log(err)} // 失败
    )
  }
  useEffect(() => {
    console.log("lasttzl",lasttzl)
    console.log("shangcitzl",shangcitzl)
    console.log("weightlist",weightlist)
  }, [])
  return (
    <>
      <UserInfo />
      <div className="jkcardpage">
        <div className="jkcon">
          {/* 健康card */}
          <div className="jkcard mgb">
          <div className="jkinfocard fl-cc wcolor">
            <div className="wusertips">
              <div>{myuserInfo.NickName} | {wdate != "Invalid date" ? wdate : "暂未"}测量</div>
              <div className="sharebtn" onClick={share}>
              </div>
            </div>
            <div className="fl-rc weightinfo">
              <div className="fl-cc">
                <div className="numtext">{ lasttzl== undefined || lasttzl.bmi==null ? "0" : lasttzl.bmi}</div>
                <div className="ttext">BMI</div>
              </div>
              <div className="weight fl-cc">
                <div className="wnum">
                  { lasttzl== undefined || lasttzl.weight_7==null ? "00.00" : lasttzl.weight_7 }
                </div>
                <div className="ttext">{weight_unit}</div>
              </div>
              <div className="fl-cc tzl">
                <div className="numtext">{ lasttzl== undefined || lasttzl.body_fat_per==null ? "0" : lasttzl.body_fat_per}<span>%</span></div>
                <div className="ttext">体脂率</div>
              </div>
            </div>
            <div className="fl-rc tipstext">
              <Mbweight/>
            </div>
            <div className="fl-rc" onClick={ljcz}>
              <span className="czbtn">立即称重</span>
            </div>
          </div>
          <div className="vstips">
            <Dbsc dbweight={dbweight} dbtzldata={dbtzldata} shangcitzl={shangcitzl}/>
          </div>
          </div>
          <div className="cardview pd mgb">
            <div className="textcolor mgb fl-rsb">
              <div className="tittext">趋势曲线</div>
              <div className="ttext">努力程度超过60%的用户</div>
            </div>
            <div className="qx-con wcolor">
              <div id="qxchart">
               <WeightEchart weightlist={weightlist !=undefined ? weightlist : [] }/>
              </div>
            </div>
          </div>
          {/* 历史数据 */}
          <div className="cardview pd mgb">
            <div className="textcolor mgb fl-rsb">
              <div className="tittext">历史数据</div>
              <div className="ttext">您已坚持测量365天</div>
            </div>
            <div className="lsjl-con wcolor fl-rsb">
              {lssj}
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
// 添加用户
function UserInfo(props) {
  var productId=props.productId
  const history = useHistory()
  function UserInfo(isinput) {
    console.log('添加用户',isinput);
    history.push('/InputUserPage',isinput)
  }
  //跳转原生解绑页面
  const showDeviceDetail = async () => {
    sdk.goDeviceDetailPage();
  };
  if(myuserInfo == sdk.userInfo){
    return (
      <div className="fl-rsbc pdlr">
        <div className="userinfo">
          <div onClick={()=>UserInfo(true)}><img src={myuserInfo.Avatar == "" ? imgrul+"headimg.png" : myuserInfo.Avatar} className="headimg"/>{myuserInfo.NickName}</div>
          <div className="mgl"><Link to={{ pathname:'/TjtwPage',state : { pagename : 'chakan' }}}><img src={imgrul+"tjtw.png"} width="18px" className="mgr5"/>添加体围 </Link></div>
          <div className="mgl"><Link to={{ pathname:'/TjtzPage',state : { pagename : 'chakan' }}}><img src={imgrul+"tjtz.png"} width="18px" className="mgr5"/>添加体重</Link> </div>
        </div>
        <div onClick={showDeviceDetail} className="detailbtn">...</div>
      </div>
    );
  }else{
    return (
      <div className="userinfo" onClick={()=>UserInfo(true)}>
        <div className="addbtn">+</div>添加用户
      </div>
    );
  }
}
// 添加体重
const minDate = new Date(1900, 1, 1, 0, 0, 0)
const maxDate = new Date(2050, 12, 31, 0, 0, 0)
function TjtzPage(props) {
  const history = useHistory()
  const dateFormat = 'YYYY/MM/DD';
  const [c_time,setc_time] = useState(moment(current_time).valueOf())
  const [weight,setweight] = useState(0)
  const weight_unit = 1
  function addtz() {
    // 增加体重
    console.log('增加体重')
    console.log(weight)
    var request = require('superAgent')
    request
    .post(apirul+'addThirdUserData')
    .send({ 
      "productId":sdk.productId,
      "deviceName":sdk.deviceName,
      "c_time":c_time,
      "weight_7":weight,
      'wx_unionid':myuserInfo.UserID,
    })
    .end(function(err, res){
      console.log(res)
      if(res.body.code == 1){
        Toast.success('增加体重成功！', 2.5)
        history.push('/Jkcard')
      }else{
        console.log('服务器链接错误'+res)
      }
    })
  }
  const onChangetz = value => {
    console.log('体重', value);
    setweight(value)
  };
  function onChangetzsj(date, dateString) {
    console.log("时间",moment(date).valueOf())
    setc_time(moment(date).valueOf())
  }
  useEffect(() => {
    // 消息订阅
    PubSub.subscribe('third_user',(msg, pubsubTest) => {		//msg 指'appData'方法， pubsubTest 指传过来的参数
      console.log("PubSub")		//appData
      // this.subTest = pubsubTest
      console.log(msg)		//appData
      console.log(pubsubTest)		//pubsubTest
      PubSub.unsubscribe("third_user");
    })
  }, [])
  return(
    <div className="TjtzPage pd">
      <div className="navtit">添加体重</div>
      <div className="itemlist pd">
          <InputItem
						placeholder="请输入"
						extra="kg"
						defaultValue={weight}
						onChange={onChangetz}
					>
          体重:
          </InputItem>
          <DatePicker
					mode="date"
					title="选择日期"
					extra={moment(c_time).format("YYYY-MM-DD")}
					minDate={minDate}
					maxDate={maxDate}
					onChange={onChangetzsj}
					>
					<List.Item arrow="horizontal">日期：</List.Item>
					</DatePicker>
      </div>
      <div className="pd fl-cc">
        <div className="pbtn" onClick={addtz}>确定</div>
      </div>
    </div>
  )
}
// 增加体围
function TjtwPage() {
  const history = useHistory()
  const [userinfo,setUserInfo] = useState(
    {shengao:"",shengri:""}
  )
  const [c_time,setc_time] = useState(moment(current_time).valueOf())
  const twinfo = {c_time:c_time,waist_around_7:0,chest_around_7:0,arm_around_7:0,thigh_around_7:0,calf_around_7:0}
  const onChangetw = (props,value) =>{
    switch(props){
      case "yw":
      twinfo.waist_around_7 = value
      break
      case "xw":
      twinfo.chest_around_7 = value
      break
      case "sbw":
      twinfo.arm_around_7 = value
      break
      case "dtw":
      twinfo.thigh_around_7 = value
      break
      case "xtw":
      twinfo.calf_around_7 = value
      break
    }
  }
  function onChangetzsj(date, dateString) {
    twinfo.c_time=moment(date).valueOf()
    setc_time(twinfo.c_time)
    console.log("时间",twinfo.c_time)
  }
  function addtw() {
    // 增加体围
    console.log('增加体围')
    var request = require('superAgent')
    request
    .post(apirul+'addThirdUserData')
    .send({ 
      "productId":sdk.productId,
      "deviceName":sdk.deviceName,
      "c_time":twinfo.c_time,
      "waist_around_7":twinfo.waist_around_7,
      "chest_around_7":twinfo.chest_around_7,
      "arm_around_7":twinfo.arm_around_7,
      "thigh_around_7":twinfo.thigh_around_7,
      "calf_around_7":twinfo.calf_around_7,
      'wx_unionid':myuserInfo.UserID,
    })
    .end(function(err, res){
      console.log(res)
      if(res.body.code == 1){
        Toast.success('增加体重成功！', 2.5)
        history.push('/Jkcard')
      }else{
        console.log('服务器链接错误'+res)
      }
    })
  }
  function handelChange(key,event){
    let form = userinfo
    console.log(key,event)
    for (let item in userinfo) {
      if (item === key) {
      form[item] = event.target.value
      setUserInfo({form: form})
      }
    }
    console.log("handelChange",userinfo)
  }
  return(
    <div className="TjtwPage pd">
      <div className="navtit">添加体围</div>
      <div className="itemlist pd">
          <InputItem
						placeholder="请输入"
						extra="cm"
            onChange={(v) => { twinfo.waist_around_7 = v}}
					>
          腰围:
          </InputItem>
          <InputItem
						placeholder="请输入"
						extra="cm"
						onChange={(v) => { twinfo.chest_around_7 = v}}
					>
          胸围:
          </InputItem>
          <InputItem
						placeholder="请输入"
						extra="cm"
						onChange={(v) => { twinfo.arm_around_7 = v}}
					>
          手臂围:
          </InputItem>
          <InputItem
						placeholder="请输入"
						extra="cm"
						onChange={(v) => { twinfo.thigh_around_7 = v}}
					>
          大腿围:
          </InputItem>
          <InputItem
						placeholder="请输入"
						extra="cm"
						onChange={(v) => { twinfo.calf_around_7 = v}}
					>
          小腿围:
          </InputItem>
          <DatePicker
					mode="date"
					title="选择日期"
					extra={moment(c_time).format("YYYY-MM-DD")}
					minDate={minDate}
					maxDate={maxDate}
					onChange={onChangetzsj}
					>
					<List.Item arrow="horizontal">日期：</List.Item>
					</DatePicker>
      </div>
      <div className="pd fl-cc">
        <div className="pbtn" onClick={addtw}>确定</div>
      </div>
    </div>
  )
}
// 历史数据
function LssjPage(){
  return(
    <div className="qsPage">
    <div className="navtit">历史数据</div>
      <div className="pd">
        <div className="pd fl-cc">
          <div className="pbtn">分享</div>
        </div>
      </div>
    </div>
  )
}
// 立即称重
export function LjczPage(props) {
  // useDeviceData包含以下值，deviceData，deviceStatus，templateMap，templateList
  const [state, {
    onDeviceDataChange,
    onDeviceStatusChange
  }] = useDeviceData(sdk);
  // 设备读取体重
  // const weight = state.deviceData.weight== undefined ? 0.00 : parseInt(parseInt(state.deviceData.weight, 16)*0.1).toString().substr(0,4)
  const weight = state.deviceData.weight== undefined ? 0.00 : parseFloat(parseInt(state.deviceData.weight, 16)*0.1).toFixed(2)
  const ZTwoLegs = state.deviceData.body_r == undefined ? 0 : parseInt(state.deviceData.body_r, 16)
  const weight_unitmode = state.templateMap.weight_unit.define.mapping
  const wuindex = state.deviceData.weight_unit == undefined ? 1 : parseInt(state.deviceData.weight_unit, 16)
  const weight_unit = weight_unitmode[wuindex]
  // 体重和单位
  const [iweight,setiweight] = useState(weight)
  const [iweight_unit,setiweight_unit] = useState(weight_unit)
  // 三方用户数据
  const para_user1 = props.para_user1;
  // 设备上报数据时间戳
  const [lastReport, setLastReport] = useState();
  // XXXX测量
  const wdate =  moment(parseInt(lastReport)).format("MM月DD日 HH:mm");
  // WebSocket 监听
  useEffect(() => {
    // 监听设备控制推送
    const handleWsControl = ({ deviceId, deviceData }) => {
      if (deviceId === sdk.deviceId) {
        onDeviceDataChange(deviceData);
      }
      console.log('Jkcard wsControl', deviceData);
    };
    // 监听设备上报数据推送
    const handleWsReport = ({ deviceId, deviceData }) => {
      if (deviceId === sdk.deviceId) {
        onDeviceDataChange(deviceData);
      }
      console.log('Jkcard wsReport', deviceId, deviceData);
    };
    // 监听设备在线状态变更推送
    const handleWsStatusChange = ({ deviceId, deviceStatus}) => {
      if (deviceId === sdk.deviceId) {
        onDeviceStatusChange(deviceStatus);
      }
      console.log('Jkcard wsStatusChange', deviceId, deviceStatus );
    };

    sdk
      .on('wsControl', handleWsControl)
      .on('wsReport', handleWsReport)
      .on('wsStatusChange', handleWsStatusChange);

    return () => {
      sdk
        .off('wsControl', handleWsControl)
        .off('wsReport', handleWsReport)
        .off('wsStatusChange', handleWsStatusChange);
    };
  }, []);
  useEffect(() => {
    console.log("weight",weight)
    console.log("ZTwoLegs",ZTwoLegs)
    console.log("wuindex",wuindex)
    console.log("weight_unitmode",weight_unitmode)
    console.log("weight_unit",weight_unit)
    if(wuindex!= null){
      switch(wuindex){
        case 1:
          setiweight(parseFloat(weight).toFixed(2))
          setiweight_unit(weight_unitmode[wuindex])
          break
        // 英镑
        case 2:
          setiweight((parseFloat(weight)*2.20462262185).toFixed(1))
          setiweight_unit(weight_unitmode[wuindex])
          break
        case 3:
          setiweight((parseFloat(weight)*2).toFixed(2))
          setiweight_unit(weight_unitmode[wuindex])
          break
        default:
          setiweight("00.00")
          setiweight_unit("KG")
          break
      }
    }
    console.log("iweight",iweight)
    PubSub.publish('iweight',iweight)//发布消息		//appDta 是发布名称，pubsubTest 是传递参数
    // 获取设备当前状态
    // const getDeviceData =(URL,props) =>{
    //   sdk.getDeviceData(sdk.deviceId).then(function(err, res){
    //     console.log('getDeviceData'+res)
    //   })
    // }
    // getDeviceData()  state.deviceData
  }, [weight]);
  const [vbtn,setVbtn] =useState(false)
  function clickvbtn(){
    setVbtn(!vbtn)
    console.log(vbtn)
  }
  // 跳转
  const history = useHistory()
  function scbg(){
    history.push('/CsbgPage',{weight,ZTwoLegs})
  }
  return (
      <div className="LjczPage fl-cc">
        <div className="vnotic" onClick={clickvbtn}>
          <img src={vbtn?imgrul+"vioce.png" : imgrul+"jingyin.png"} />
        </div>
        <div className="mgtb">
        <div className="bigheadimg"><img src={myuserInfo.Avatar == "" ? imgrul+"headimg.png" : myuserInfo.Avatar}/></div>
        </div>
        <div className="mgb">{myuserInfo.NickName}</div>
        <div className="ljcztips">
        请光脚站立在秤上<br/>
        早上空腹便后测量更精确
        </div>
        <div className="ljcznum fl-cc">
          <div className="ljczbg fl-cc">
            <div className="weight fl-rc">
              <div className="wnum">
                {iweight}
                {/* { weight!= null ? weight : "00.00"} */}
              </div>
              <div className="tittext mgl">
              {iweight_unit}
              {/* {weight_unit} */}
              </div>
            </div>
          </div>
        </div>
        <div className="fl-cc pd mgt"><span className="czbtn" onClick={scbg}>查看报告</span></div>
      </div>
  );
}
// 测试报告
function CsbgPage(props) {
  const history = useHistory()
  // 设备状态
  const {weight,ZTwoLegs} = history.location.state || {}
  const para_user1 = props.para_user1
  const weight_unit = props.weight_unit;
  // 雷达图数据
  const [bodyinfores,setbodyinfores]  = useState([])
  const [bodyinfovalue,setbodyinfovalue] = useState([])
  const bodyinfores1 = useRef()
  const bodyinfovalue1 = useRef()
  // 设备状态
  const [lasttzl, setlasttzl] = useState([]);
  const lastweight = lasttzl!= undefined ? lasttzl.weight : 0.00
  const dbsctime =lasttzl!=undefined ? moment(parseInt(lasttzl.c_time)).format("YYYY/MM/DD") : "暂无"
  // 身体数据(计算后的体脂等数据)
  const [bodyInfo, setbodyInfo] = useState({});
  const current_time = (new Date()).valueOf()
  var age = matAge(parseInt(para_user1.current.birthday),parseInt(current_time))
  function getBodyInfo(para_user1) {
    // 获取身体数据
    console.log('开始获取身体数据',para_user1.current)
    var request = require('superAgent')
    request
    .post('https://iotapi.sziton.com/api/ex_inter_face_info/getBodyInfo')
    .send({ 
      "age":age,
      "height":parseInt(para_user1.current.height),
      "sex":parseInt(para_user1.current.sex),
      "impedance":139,
      "weightKg":8000,
      // "impedance":ZTwoLegs,
      // "weightKg":parseInt(weight)*100,
      "c_type":c_type
    })
    .end(function(err, res){
      if(res.body.code == 1){
        var bdinfo = res.body.data
        console.log('身体数据如下：')
        console.error("3")
        if(Object.keys(bdinfo).length > 0){
          console.log(bdinfo.details)
          setbodyInfo(bdinfo.details)
          const pubsubTest = bdinfo.details
          const tempres =[
            { name: '体脂'+checkAdult(pubsubTest.ratioOfFatRange,pubsubTest.ratioOfFat,resFatRange1),max:30,min: 0},
            { name: '肌肉'+checkAdult(pubsubTest.ratioOfMuscleRange,pubsubTest.ratioOfMuscle,resFatRange1), max: 120,min: 5},
            { name: '内脂'+checkAdult(pubsubTest.levelOfVisceralFatRange,pubsubTest.levelOfVisceralFat,resFatRange1), max: 60,min: 5},
            { name: '水分'+checkAdult(pubsubTest.ratioOfWaterRange,pubsubTest.ratioOfWater,resFatRange1), max: 750,min: 5},
            { name: '骨量'+checkAdult(pubsubTest.weightOfBoneRange,pubsubTest.weightOfBone,resFatRange1), max: 8,min: 5},
            { name: 'BMI'+checkAdult(pubsubTest.bmiRange,pubsubTest.bmi,resFatRange1), max: 90,min: 5},
            { name: '蛋白'+checkAdult(pubsubTest.weightOfProteinRange,pubsubTest.weightOfProtein,resFatRange1), max: 18,min: 5},
          ]
          bodyinfores1.current = tempres
          const tempval =[
            pubsubTest.ratioOfFat,
            pubsubTest.ratioOfMuscle,
            pubsubTest.levelOfVisceralFat,
            pubsubTest.ratioOfWater,
            pubsubTest.weightOfBone,
            pubsubTest.bmi,
            pubsubTest.weightOfProtein
          ]
          bodyinfovalue1.current = tempval
          setbodyinfores(tempres)
          console.error("tempres")
          console.error(bodyinfores1)
          console.error(bodyinfovalue1)
          PubSub.publish('pbdinfo',bdinfo.details)
        }else{
          Toast.fail('服务器返回数据为空！', 2)
        }
      }else{
        console.log('服务器'+res)
      }
    })
  }
  const bodyinfores2 =[
    { name: '体脂'+checkAdult(bodyInfo.ratioOfFatRange,bodyInfo.ratioOfFat,resFatRange1),max:40.5,min: 0},
    { name: '肌肉'+checkAdult(bodyInfo.ratioOfMuscleRange,bodyInfo.ratioOfMuscle,resFatRange1), max: 160.8,min: 0},
    { name: '内脂'+checkAdult(bodyInfo.levelOfVisceralFatRange,bodyInfo.levelOfVisceralFat,resFatRange1), max:21.0,min: 0},
    { name: '水分'+checkAdult(bodyInfo.ratioOfWaterRange,bodyInfo.ratioOfWater,resFatRange1), max: 97.5,min: 0},
    { name: '骨量'+checkAdult(bodyInfo.weightOfBoneRange,bodyInfo.weightOfBone,resFatRange1), max: 4.1,min: 0},
    { name: 'BMI'+checkAdult(bodyInfo.bmiRange,bodyInfo.bmi,resFatRange1), max:42.0,min: 0},
    { name: '蛋白'+checkAdult(bodyInfo.weightOfProteinRange,bodyInfo.weightOfProtein,resFatRange1), max: 15.0,min: 0},
  ]
  const bodyinfovalue2 =[
    bodyInfo.ratioOfFat,
    bodyInfo.ratioOfMuscle,
    bodyInfo.levelOfVisceralFat,
    bodyInfo.ratioOfWater,
    bodyInfo.weightOfBone,
    bodyInfo.bmi,
    bodyInfo.weightOfProtein
  ]
  // 测试报告echart
  const echartopts = {
    radar: {
      indicator: bodyinfores2!=undefined ? bodyinfores2 :[{ name: '暂无', max: 0}]
    },
    series: [{
      name: '预算 vs 开销（Budget vs spending）',
      type: 'radar',
      color: '#2DD4AF',
      data: [
          {
              value: bodyinfovalue2!=undefined ? bodyinfovalue2 : [0],
              name: '预算分配（Allocated Budget）'
          }
      ],
      symbol:'emptyCircle', 
      symbolSize :3,
      label:{
        show:true,
        color:'#2DD4AF'
      },
      labelLine:{
        show:true,
        color:'#2DD4AF'
      },
      lineStyle:{
        color:'#2DD4AF',
        width:2
      },
      areaStyle:{
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
              offset: 0, color:'rgba(45, 212, 175, 1)' // 0% 处的颜色
          }, {
              offset: 1, color:'rgba(45, 212, 175, 0)' // 100% 处的颜色
          }],
          global: false // 缺省为 false
        },
        shadowColor: 'rgba(255, 255, 255, 0.5)',
        shadowBlur: 8,
        opacity:0.3
      }
    }]
  };
  useEffect(() => {
    getBodyInfo(para_user1)
    PubSub.subscribe('pbdinfo',(msg, pubsubTest) => {
      console.log("pbdinfoPubSub")
      console.log(msg)
      console.log(pubsubTest)
      PubSub.unsubscribe("pbdinfo");
    })
  }, []);
  // 数据上报
  function sbtz(){
    console.log("时间",moment(current_time).valueOf())
    var request = require('superAgent')
    request
    .post(apirul+'addThirdUserData')
    .send({
      "productId":sdk.productId,
      "deviceName":sdk.deviceName,
      'wx_unionid':myuserInfo.UserID,
      "c_time":moment(current_time).valueOf(),
      // "c_time":Math.round(new Date() / 1000),
      "weight_7":weight,
      "weight_7_u":weight_unit,
      "bmi":bodyInfo.BMI,
      "bmr":bodyInfo.BMR,
      "body_fat_per":bodyInfo.BodyfatPercentage,//体脂
      "bone":bodyInfo.BoneKg,//骨量
      "muscle":bodyInfo.Muscle,//肌肉量
      "water_percentage":bodyInfo.WaterPercentage
    })
    .end(function(err, res){
      if(res.code = 1){
        Toast.success('更新成功！', 2.5)
      }else{
        Toast.fail('更新失败！', 1)
        console.log('服务器'+res.status,res)
      }
      console.log(res.status)
    })
  }
  return(
    <div className="CsbgPage">
      <div className="navtit">测试报告</div>
      <div className="weightldt pd">
        {bodyInfo!=undefined && echartopts!=undefined && (
          <ReactEChartsCore
            echarts={echarts}
            option={echartopts}
            notMerge={true}
            lazyUpdate={true}
            theme={"theme_name"}
            style={{ height: '300px', width: '100%' }}
          />
        )}
        <div className="weight fl-cc">
          <div className="wnum">
            { bodyInfo.weight!= null ? bodyInfo.weight : "00.00"}
          </div>
          <div className="ttext">{weight_unit}</div>
        </div>
      </div>
      <div className="fl-cc pd">
        <div className="pd"></div>
        <div className="fl-rsb stpf mgb bd1">
          <div className="fl-cc">
            <span>身体评分</span>
            <span>{bodyInfo.score}分</span>
          </div>
          <div className="fl-cc">
            <span>体型</span>
            <span>{resbodyShape[bodyInfo.bodyShape]}</span>
          </div>
        </div>
      </div>
      <div className="pd">
        {bodyInfo!=undefined && (<Bmiline bmi={bodyInfo.bmi} bmiRange={bodyInfo.bmiRange}/>)}
      </div>
      {/* <div className="vstips pd">
        <div className="tittext">对比上次（{dbsctime})</div>
        <div className="mgb bd1">
          <Dbsc dbweight={bodyInfo.weight} dbtzldata={dbtzldata} shangcitzl={lastweight}/> 
        </div>
      </div>*/}
      <div className="tittext pd">全部</div> 
        {bodyInfo!=undefined && (<Bdtlist bodyInfo={bodyInfo}/>)}
      <div className="bgzjtext pd">
      基础代谢率（Basal Metabolic Rate，简称BMR）是指：我们在安静状态下(通常为静卧状态)消耗的最低热量，人的其他活动都建立在这个基础上。
      </div>
      <div className="bottomtips">—— 非医疗数据，仅供参考 ——</div>
      <div className="float-con">
        <div className="fl-cc floatbtn"><div className="pbtn">分享</div></div>
      </div>
      <div className="pd fl-cc" onClick={sbtz}>
        <div className="pbtn">保存报告</div>
      </div>
    </div>
  )
}
//定义reducer
export default function ReducerDemo() {
  const [count, dispath] = useReducer((state,action)=> {
    if(action === 'add'){
        return state + 1;
    }
    return state;
  }, 0);
  return (
      <div>
          <h1 className="title">{count}</h1>
            <button className="btn is-primary"
                onClick={()=> dispath('add')}
                >Increment</button>
      </div>
  )
}
// 获取接口数据
const getData =(URL,props) =>{
  return new Promise(function (resolve, reject) {
    var request = require('superAgent')
    request
    .post(URL)
    .send(props)
    .end(function(err, res){
      if(res.body.code == 1){
        resolve(res.body.data);
      }else{
        console.log('服务器错误'+res)
        reject(new Error(res.statusText));
      }
      request.onerror = function () {
          reject(new Error(request.statusText));
      };
    })
  });
}
// 计算年龄
const matAge=(bir,c_time)=>{
	var age = Math.ceil((c_time-bir)/31536000000);
	return age
}
// 数据对比
const checkAdult = (reslist,val,resrange) =>{
  var resindex = 0
  if(reslist!=undefined && reslist.length > 0){
    reslist.map((item,i)=>{
      if(val > reslist[i] && val < reslist[i+1]){
        resindex = i
      }
    })
    // console.log(reslist+"---"+resrange[resindex])
    return resrange[resindex]
  }else{
    return "暂无"
  }
}
// 查找样式
const bdwstate=(v)=>{
  var level = "gr"
  switch(v){
    case "不⾜": case "偏瘦": case "偏低": case "缺失": case "较轻": case "无": case "营养不良" : case "轻度肥胖" :
      level = "pt"
      break
    case "过轻": case "偏胖": case "偏胖型": case "轻度肥胖": case "中度营养不良": case "过重": case "警戒":
      level = "pg"
      break
    case "隐性胖": case "中度肥胖": case "营养过剩": case "偏瘦型": case "运动型偏胖": case "偏⾼": case  "肥胖":
      level = "pt"
      break
    case "标准": case  "健康" : case "正常" : case "偏瘦运动型": case  "标准型":
      level = "bz"
      break
    case "优": case  "标准运动型": case  "运动健美型" :
      level = "gg"
      break
    case "极度肥胖": case  "重度肥胖": case  "营养严重过剩": case "营养过剩": case "严重营养不良": case  "缺乏锻炼型": case "严重偏⾼":
      level = "yz"
      break
  }
  return level
}
// 数据列表
const Bdtlist =(props)=>{
  const bodyInfo = props.bodyInfo
  const [bdtlistInfo, setbdtlistInfo] = useState([
    {text:"无",val:"0",valres:"暂无"}
  ]);
  useEffect(() => {
    console.log("数据列表Bdtlist")
    console.log(props)
  }, []);
  return(
    <>
      <div className="bdtlist">
        {/* <ReducerDemo/> */}
        <div className="fl-rsbc bd1 pd">
          <div className="bdlimg"><img src={imgrul+"tz.png"}/><span>体重</span></div>
          <div>{ bodyInfo.weight}</div>
          <div><span className={classNames("wstate", bdwstate(checkAdult(bodyInfo.weightRange,bodyInfo.weight,resweightRange)))}>{checkAdult(bodyInfo.weightRange,bodyInfo.weight,resweightRange)}</span></div>
        </div> 
        <div className="fl-rsbc bd1 pd">
          <div className="bdlimg"><img src={imgrul+"yyzt.png"}/><span>营养状态</span></div>
          <div>{ bodyInfo.stateOfNutrition}</div>
          <div><span className={classNames("wstate", bdwstate(resNutrition[bodyInfo.stateOfNutrition]))}>{resNutrition[bodyInfo.stateOfNutrition]}</span></div>
        </div>
        <div className="fl-rsbc bd1 pd">
          <div className="bdlimg"><img src={imgrul+"rzxl.png"}/><span>燃脂心率</span></div>
          <div>0次/分钟</div>
          {/* <div>{bodyInfo!=undefined ? bodyInfo.rateOfBurnFat.max : ""}</div> */}
        </div>
        <div className="fl-rsbc bd1 pd">
          <div className="bdlimg"><img src={imgrul+"kll.png"}/><span>BMR</span></div>
          <div>{bodyInfo.bmr}</div>
          <div><span className={classNames("wstate", bdwstate(checkAdult(bodyInfo.bmrRange,bodyInfo.bmr,resbmrRange)))}>{checkAdult(bodyInfo.bmrRange,bodyInfo.bmr,resbmrRange)}</span></div>
        </div>
        <div className="fl-rsbc bd1 pd">
          <div className="bdlimg"><img src={imgrul+"nzzf.png"}/><span>内脏脂肪</span></div>
          <div>{bodyInfo.levelOfVisceralFat}</div>
          <div><span className={classNames("wstate", bdwstate(checkAdult(bodyInfo.levelOfVisceralFatRange,bodyInfo.levelOfVisceralFat,resFatRange)))}>{checkAdult(bodyInfo.levelOfVisceralFatRange,bodyInfo.levelOfVisceralFat,resFatRange)}</span></div>
        </div>
        <div className="fl-rsbc bd1 pd">
          <div className="bdlimg"><img src={imgrul+"tx.png"}/><span>肥胖等级</span></div>
          <div>{bodyInfo.obesityLevel}</div>
          <div><span className={classNames("wstate",bdwstate(checkAdult(bodyInfo.obesityLevelList,bodyInfo.obesityLevel,resobesity)))}>{checkAdult(bodyInfo.obesityLevelList,bodyInfo.obesityLevel,resobesity)}</span></div>
        </div>
        <div className="fl-rsbc bd1 pd">
          <div className="bdlimg"><img src={imgrul+"zfhl.png"}/><span>体脂率</span></div>
          <div>{bodyInfo.ratioOfFat}</div>
          <div><span className={classNames("wstate",bdwstate(checkAdult(bodyInfo.ratioOfFatRange,bodyInfo.ratioOfFat,resFatRange1)))}>{checkAdult(bodyInfo.ratioOfFatRange,bodyInfo.ratioOfFat,resFatRange1)}</span></div>
        </div>
        <div className="fl-rsbc bd1 pd">
          <div className="bdlimg"><img src={imgrul+"jrl.png"}/><span>肌⾁率</span></div>
          <div>{bodyInfo.ratioOfMuscle}</div>
          <div><span className={classNames("wstate",bdwstate(checkAdult(bodyInfo.ratioOfMuscleRange,bodyInfo.ratioOfMuscle,resMuscleRange)))}>{checkAdult(bodyInfo.ratioOfMuscleRange,bodyInfo.ratioOfMuscle,resMuscleRange)}</span></div>
        </div>
        <div className="fl-rsbc bd1 pd">
          <div className="bdlimg"><img src={imgrul+"dbzhl.png"}/><span>蛋⽩质率</span></div>
          <div>{bodyInfo.ratioOfProtein}</div>
          <div><span className={classNames("wstate",bdwstate(checkAdult(bodyInfo.ratioOfProteinRange,bodyInfo.ratioOfProtein,resMuscleRange)))}>{checkAdult(bodyInfo.ratioOfProteinRange,bodyInfo.ratioOfProtein,resMuscleRange)}</span></div>
        </div>
        <div className="fl-rsbc bd1 pd">
          <div className="bdlimg"><img src={imgrul+"ggjzl.png"}/><span>⻣骼肌率</span></div>
          <div>{bodyInfo.ratioOfSkeletalMuscle}</div>
          <div><span className={classNames("wstate",bdwstate(checkAdult(bodyInfo.ratioOfSkeletalMuscleRange,bodyInfo.ratioOfSkeletalMuscle,resMuscleRange)))}>{checkAdult(bodyInfo.ratioOfSkeletalMuscleRange,bodyInfo.ratioOfSkeletalMuscle,resMuscleRange)}</span></div>
        </div>
        <div className="fl-rsbc bd1 pd">
          <div className="bdlimg"><img src={imgrul+"pxzf.png"}/><span>⽪下脂肪率</span></div>
          <div>{bodyInfo.ratioOfSubcutaneousFat}</div>
          <div><span className={classNames("wstate",bdwstate(checkAdult(bodyInfo.ratioOfSubcutaneousFatRange,bodyInfo.ratioOfSubcutaneousFat,resFatRange2)))}>{checkAdult(bodyInfo.ratioOfSubcutaneousFatRange,bodyInfo.ratioOfSubcutaneousFat,resFatRange2)}</span></div>
        </div>
        <div className="fl-rsbc bd1 pd">
          <div className="bdlimg"><img src={imgrul+"shl.png"}/><span>⽔份率</span></div>
          <div>{bodyInfo.ratioOfWater}</div>
          <div><span className={classNames("wstate",bdwstate(checkAdult(bodyInfo.ratioOfWaterRange,bodyInfo.ratioOfWater,resWaterRange)))}>{checkAdult(bodyInfo.ratioOfWaterRange,bodyInfo.ratioOfWater,resWaterRange)}</span></div>
        </div>
        <div className="fl-rsbc bd1 pd">
          <div className="bdlimg"><img src={imgrul+"ggzl.png"}/><span>⻣量</span></div>
          <div>{bodyInfo.weightOfBone}</div>
          <div><span className={classNames("wstate",bdwstate(checkAdult(bodyInfo.weightOfBoneRange,bodyInfo.weightOfBone,resBoneRange)))}>{checkAdult(bodyInfo.weightOfBoneRange,bodyInfo.weightOfBone,resBoneRange)}</span></div>
        </div>
        <div className="fl-rsbc bd1 pd">
          <div className="bdlimg"><img src={imgrul+"zfzl.png"}/><span>脂肪重量</span></div>
          <div>{bodyInfo.weightOfFat}</div>
          <div><span className={classNames("wstate",bdwstate(checkAdult(bodyInfo.weightOfFatRange,bodyInfo.weightOfFat,resFatRange1)))}>{checkAdult(bodyInfo.weightOfFatRange,bodyInfo.weightOfFat,resFatRange1)}</span></div>
        </div>
        <div className="fl-rsbc bd1 pd">
          <div className="bdlimg"><img src={imgrul+"jrzl.png"}/><span>肌⾁重量</span></div>
          <div>{bodyInfo.weightOfMuscle}</div>
          <div><span className={classNames("wstate",bdwstate(checkAdult(bodyInfo.weightOfMuscleRange,bodyInfo.weightOfMuscle,resMuscleRange)))}>{checkAdult(bodyInfo.weightOfMuscleRange,bodyInfo.weightOfMuscle,resMuscleRange)}</span></div>
        </div>
        <div className="fl-rsbc bd1 pd">
          <div className="bdlimg"><img src={imgrul+"dbzzl.png"}/><span>蛋⽩质重量</span></div>
          <div>{bodyInfo.weightOfProtein}</div>
          <div><span className={classNames("wstate",bdwstate(checkAdult(bodyInfo.weightOfProteinRange,bodyInfo.weightOfProtein,resMuscleRange)))}>{checkAdult(bodyInfo.weightOfProteinRange,bodyInfo.weightOfProtein,resMuscleRange)}</span></div>
        </div>
        <div className="fl-rsbc bd1 pd">
          <div className="bdlimg"><img src={imgrul+"szl.png"}/><span>⽔份重量</span></div>
          <div>{bodyInfo.weightOfWater}</div>
          <div><span className={classNames("wstate",bdwstate(checkAdult(bodyInfo.weightOfWaterRange,bodyInfo.weightOfWater,resWaterRange)))}>{checkAdult(bodyInfo.weightOfWaterRange,bodyInfo.weightOfWater,resWaterRange)}</span></div>
        </div>
      </div>
    </>
  )
}
// 对比上次
const Dbsc = (props) =>{
  const dbweight =props.dbweight
  const dbtzldata = props.dbtzldata
  const Dbtzl = () => {
    if (dbtzldata == null){return 0}
    else if (dbtzldata > 0){return dbtzldata}
    else {return Math.abs(dbtzldata)}
  }
  const shangcitzl=props.shangcitzl
  const weight_unit = "kg"
  return (
  <div className="fl-rsb pd">
    <div className="fl-rc dbsc">
      <div className="fl-cc mgr5"><img src={imgrul+"VS.png"}/></div>
      <div className="fl-cc">
        <div className="tittext">对比上次</div>
        <div className="ttext">{shangcitzl!= null ? moment(parseInt(shangcitzl.option_time)).format("YYYY/MM/DD"): "暂无"}</div>
      </div>
    </div>
    <div className="fl-rc">
      <div className="fl-cc">
        <div className="numtext">{dbweight > 0 ? dbweight : Math.abs(dbweight)}<span>{weight_unit}</span></div>
        <div className="ttext">体重{dbweight > 0 ? "增加" : "减少"}</div>
      </div>
      <div className="fl-cc upicon">
        <img src={dbweight > 0 ? imgrul+"up.png" : imgrul+"down.png"} />
      </div>
    </div>
    <div className="fl-rc">
      <div className="fl-cc tzjd">
        <div className="numtext"><Dbtzl/><span>%</span></div>
        <div className="ttext">体脂{dbtzldata > 0 ? "升高" : "降低"}</div>
      </div>
      <div className="fl-cc upicon">
        <img src={dbtzldata > 0 ? imgrul+"up.png" : imgrul+"down.png"}/>
      </div>
    </div>
  </div>
  )
}
// Bmi信息
const Bmiline =(props)=>{
  const bmi=props.bmi
  const bmiRange=props.bmiRange
  useEffect(() => {
    console.log("数据列表Bmiline")
    console.log(props)
  }, []);
  return(
    <div className="prog tsize mgtb">
      <div className="prog-tit">
        {bmiRange!=undefined && bmiRange.map((item,i)=>
          <span key={i}>{item}</span>
        )}
      </div>
      <div className="prog-bar fl-rc mgtb">
        {bmiRange!=undefined && bmiRange.map((item,i,arr)=>
          <span key={i} className={classNames({"selected": bmi>item && bmi<arr[i+1]})}></span>
        )}
      </div>
      <div className="prog-desc">
        {resbmiWHORange.map((item,i)=>
          <span key={i}>{item}</span>
        )}
      </div>
    </div>
  )
}